var soundList = ['Do_aigu', 'Do_grave', 'Do_Medium', 'Fa_aigu', 'Fa_grave', 'Fa_Medium', 'La-aigu', 'La_grave', 'La_medium', 'Mi_aigu', 'Mi_grave', 'Mi_medium', 'Re_Aigu', 'Re_grave', 'Re_grave_2', 'Re_Medium', 'Si_aigu', 'Si_grave', 'Si_Medium', 'Sol_aigu', 'Sol_grave', 'Sol_medium'];
var soundNumber = soundList.length;
var sounds = new Array();

var mouseDuration;
var mouseDownTime;
var mouseAutomationTimer;

var textsFR = ['Impossible de charger les phrases.', 'no'];
var textsEN = ['Can`t load sentences.', 'non'];
var textEN = textsEN[0];
var textFR = textsFR[0];

var modeAuto = true;
var selectedSpan = null;

var sound_on = true;
var wave = 0;
var index = 0;
var lastTap = 0;

var eventInProgress = false;
var tapHolding = false;
var scrolling = false;
var phraseInput;

var startX;
var startY;
var indexList;
var sizeList;
var ulList;
var timerScroll;
var waitTime = 2000;
var toDelete = false;
var timerDel;
var timerOpacity;
var cptOpacity;
var synonymeList;

var determinants = ["d'un", "d'une", "d’un", "d’une", 'un', 'une', 'le', 'la', "l'", 'mon', 'ton', 'son', 'ma', 'ta', 'sa', 'cet', 'cette'];

function trim(myString) {
	return myString.replace(/^\s+/g, '').replace(/\s+$/g, '')
}

function appendToCloud(phrase) {
	var h = $(document).height() - 270 - $('#mainPhrase').height();
	$('#cloud').append('<div class="derive" style="top: ' + h + 'px;">' + phrase + '</div>');
	moveClouds();
}

function moveClouds() {
	var h = $(document).height() - 270 - $('#mainPhrase').height();

	var n = $('#cloud div').length;
	$.each($('#cloud div'), function (i, el) {
		wave++;
		el = $(el);

		newTop = i * (h / 7);

		el.animate({
			top: newTop + 'px',
			opacity: 0.1 + (i / 7),
			fontSize: 10 + (i / 7) * 10,
			left: 100 * Math.sin(wave)
		}, 'slow');
		if (i > 5) {
			$('#cloud div:first').remove();
		}
	});

}

function morphText() {
	var reg = new RegExp("[ ,;\.\r\n]+", "g");
	var wholeText = '';
	$.each($('#mainPhrase').text().split(reg), function (i, el) {
		wholeText = wholeText + ' <span>' + trim(el) + '</span>';
	});

	wholeText = wholeText.replace(/<span>\*([^\<]*)\*<\/span>/g, "$1");
	wholeText = wholeText.replace(/_/g, ' ')
	$('#mainPhrase').html(wholeText);
}

function inputFCT() {
	phraseInput = $('#mainPhrase').text();
	$('#inputSpace').html('<input type="text" name="phrase" id="userInput" value="'+phraseInput+'" data-theme="c"/>');
	$('#userInput').focus();
	$.mobile.changePage($('#input'), "pop");
	
	return false;
}

function Exchange(e) {
	elt = $(e).text();
	previous = $(e).prev().text();
	if (elt.length > 3 && !$(e).hasClass('loading')) {
		$(e).addClass('loading');
		$.ajax({
			url: "getSynonyme.php",
			dataType: 'json',
			data: {
				word: encodeURIComponent(elt),
				previous: encodeURIComponent(previous),
				lang: lang
			},
			success: function (data) {
				$(e).removeClass('loading');
				var syns = data.syns;
				if (syns.length != 0) {
					var len = syns.length;
					var rand = Math.floor(Math.random() * len);
					previous = $(e).prev().text();
					if (determinants.indexOf(previous) != -1) {
						$(e).prev().remove();
					}
					syns[rand] = '<span>' + syns[rand] + '</span>';
					syns[rand] = syns[rand].replace(/\+/g, '</span> <span>');
					syns[rand] = syns[rand].replace(/_/g, ' ');
					$(e).after(syns[rand]).remove();
					playRandomNote();
					eventInProgress = false;
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log(textStatus, errorThrown);
				$(e).removeClass('loading');
				playRandomNote();
			}
		});
	}
}

function Choose(e) {
	if (selectedSpan == null) {
		elt = $(e).text();
		previous = $(e).prev().text();
		if (elt.length > 3 && !$(e).hasClass('loading')) {
			$(e).addClass('loading');
			
			$.ajax({
				url: "getSynonyme.php",
				dataType: 'json',
				data: {
					word: encodeURIComponent(elt),
					lang: lang
				},
				success: function (data) {
					var syns = data.syns;
					if (syns.length != 0) {
						var len = syns.length;
						var left;
						var ul = '<ul id="ul">';
						var padding = 40;
						var maxWidth;
						
						indexList = 1;
						sizeList = 0;
						ul += '<li>' + $(e).text() + '</li>';
						
						if (syns.length >= 7)
							for (i = 0; i < 7; i++)
							{
								ul += '<li>' + syns[i] + '</li>';
								sizeList++;
							}
						else
							$.each(syns, function (i, el) {
								ul += '<li>' + syns[i] + '</li>';
								sizeList++;
							});
						sizeList++;
						ul += '<li><img src="./delete.png" /></li>';
						ul += '</ul>';
						
						synonymeList = syns;
						$("#selector").html(ul);
						
						// récupérer l'ensemble des enfants de #ul
						ulList = $("#ul").children("li");
						ulList.eq(indexList).addClass('li-selected');
						
						maxWidth = $('#ul').width() + padding;
						left = $(e).offset().left - (($("#ul").width()-$(e).width()) / 2) - padding/2;
						if (left < 0) { left = 0; }
						
						$("#ul").css({
							'position': 'absolute',
							'top': $(e).offset().top+10,
							'left': left,
							'width': maxWidth+'px',
							'padding-left': '0px',
							'padding-right': '0px',
							'text-align': 'center' 
						});
						selectedSpan = $(e);
						$(e).attr('id','selectedSpan');
						timerScroll = setTimeout("scrollTimeOut()", waitTime);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$(e).removeClass('loading');
				}
			});
		}
	}
}

function Select(e) {
	var str;
	
	$('#ul').remove();
	selectedSpan.removeClass('loading');
	
	if (toDelete) {
		str = $('#mainPhrase').text();
		appendToCloud(str);
		deleteSpan();
	} else {
		if (!(e.text() == $(selectedSpan).text())) {
			str = $('#mainPhrase').text();
			appendToCloud(str);
			$(selectedSpan).html(e.text());
		}
		$('#selectedSpan').attr('id','');
		eventInProgress = false;
		tapHolding = false;
		selectedSpan = null;
	}
}

function scrollTimeOut() {
	Select($('.li-selected'));
	playRandomNote();
}

function fetchPhrases() {
	$.ajax({
		url: "phrases." + lang + ".txt",
		dataType: 'txt',
		success: function (data) {
			console.log(lang);
			if (lang == 'FR') {
				textsFR = data.responseText.split("\n");
				$('#mainPhrase').html(textsFR[index]);
			} else if (lang == 'EN') {
				textsEN = data.responseText.split("\n");
				$('#mainPhrase').html(textsEN[index]);
			}
			morphText();
			index++;
		},
		error: function (data) {
			if (lang == 'FR') {
				textsFR = data.responseText.split("\n");
				$('#mainPhrase').html(textsFR[index]);
			} else if (lang == 'EN') {
				textsEN = data.responseText.split("\n");
				$('#mainPhrase').html(textsEN[index]);
			}
			morphText();
			index++;
		}
	});
}

function playRandomNote() {
	if (sound_on) {
		i = $.random(soundNumber);
		sounds[i].play();
	}
}

function deleteSpan() {
	var allSpan = $('#mainPhrase').children('span');
	var str = '';
	var delSpan;
	var top;
	var left;
	var dist;
	var time = 3000;
	
	for (var i = 0; i < allSpan.length; i++) {
		if ($(allSpan[i]).attr('id') == 'selectedSpan') {
			delSpan = allSpan[i];
		} else {
			str += '<span>'+$(allSpan[i]).text()+'</span> ';
		}
	}
	
	top = parseInt($(delSpan).offset().top);
	left = parseInt($(delSpan).offset().left);
	dist = $(window).height()-top;
	
	$('#fadingWord').html($(delSpan).text());
	$('#fadingWord').css({
		'top':top+'px',
		'left':left+'px',
		'position':'absolute',
	});
	
	var timeOut = parseInt(($('#fadingWord').height()*time/dist)/2);
	
	$('#fadingWord').show();
	
	cptOpacity = 0;
	timerDel = setTimeout("addTempTimeOut("+timeOut+")", timeOut);
	timerOpacity = setTimeout("changeOpacityTimeOut()", 50);
	
	$(delSpan).fadeOut(time);
	$('#fadingWord').animate({
		top: $(window).height()+'px'
	}, time-500, 'linear', function() {
		toDelete= false;
		clearTimeout(timerDel);
		$('#fadingWord').fadeOut(500,function() {
			$('#fadingWord').empty();
			eventInProgress = false;
			tapHolding = false;
			selectedSpan = null;
			$('#mainPhrase').html(str);
		});
	});
}

function changeOpacityTimeOut() {
	var allTemp = $('#trace').children(':visible');
	for (var i = 0; i < allTemp.length; i++) {
		var opacity = parseFloat($(allTemp[i]).css('opacity')) - 0.05;
		$(allTemp[i]).css('opacity',opacity);
		
		if (opacity < 0.1) {
			$(allTemp[i]).hide();
			cptOpacity--;
			if (cptOpacity == 0) {
				$('#trace').empty();
				return;
			}
		}
	}
	timerOpacity = setTimeout("changeOpacityTimeOut()", 50);
}

function addTempTimeOut(timeOut) {
		$('#fadingWord').text(nextWord());
		var word = $('#fadingWord');
		var allTemp = $('#trace').children();
		var cpt = allTemp.length;
		var str = '<span id="temp_'+cpt+'">'+word.text()+'</span>';
		
		$('#trace').html($('#trace').html()+str);
		$('#temp_'+cpt).css('top',word.css('top'));
		$('#temp_'+cpt).css('left',word.css('left'));
		$('#temp_'+cpt).css('opacity',word.css('opacity'));
		$('#temp_'+cpt).css('position','absolute');
		cptOpacity++;
		
		if (toDelete) {
			timerDel = setTimeout("addTempTimeOut("+timeOut+")", timeOut);
		}
}

function nextWord() {
	var word = synonymeList.pop();
	synonymeList.reverse();
	synonymeList.push(word);
	synonymeList.reverse();
	
	return word;
}

function changerPhrase() {
	if (!eventInProgress) {
		$.each($('#mainPhrase span'), function (i, e) {
			Exchange(e);
		});
		appendToCloud($('#mainPhrase').text());
	}
}

$('#index').ready(function (event) {	// se lance au chargement de la page d'accueil, ne devrait il pas se lancer au chargement de la 2nd page uniquement ? 
	for (var i = 0; i < soundList.length; i++) {
		sounds.push(new buzz.sound("/sounds/" + soundList[i], {
			formats: ["ogg", "mp3"],
			preload: true
		}));
	}

	var sound_background = new buzz.sound("/sounds/changerTout", {
		formats: ["ogg", "mp3"],
		preload: true,
		autoplay: true,
		loop: true
	});
	
	//PARTIE METTANT A JOUR 'MAIN PHRASE' ET LA DECOUPANT EN SPAN
	
	console.log(userInput);
	if (userInput == '') {
		fetchPhrases();
	} else {
		$('#mainPhrase').html(userInput);
		morphText();
	}
	
	$('#sound').load(function() {
		$('#sound').css({
			'top':($(window).height()-$('#sound').height())+'px',
			'left':($(window).width()-$('#sound').width())+'px'
		});
	});
	
	$('#sound').bind('tap', function () {
		if (sound_on) {
			sound_background.pause();
			$('#sound').attr('src','./sound_off.png');
		} else {
			sound_background.play();
			$('#sound').attr('src','./sound.png');
		}
		sound_on = !sound_on;
	});
	
	$('#mainPhrase').delegate('span', 'tap', function(e) {
		e.stopPropagation();
		if (!eventInProgress) {
			eventInProgress = true;
			lastTap = (new Date()).getTime();
			if(!$(this).hasClass('loading') && ($(this).text().length > 3)) {
				phrase = $('#mainPhrase').text();
				appendToCloud(phrase);
				Exchange(this);
			} else {
				eventInProgress = false;
			}
		}
	});
	
	$('#mainPhrase').delegate('span', 'taphold', function(e) {
		e.stopPropagation();
		if (!eventInProgress) {
			eventInProgress = true;
			tapHolding = true;
			if(!$(this).hasClass('loading') && ($(this).text().length > 3)) {
				Choose(this);
			} else {
				eventInProgress = false;
				tapHolding = false;
			}
		}
	});
	
	$('#mainPhrase').swipeleft(function() {
		if (!eventInProgress) {
			eventInProgress = true;
			$('#mainPhrase').hide("slide", { direction: "left" }, 1000, function() {
				index -= 2;
				if (lang == 'FR') {
					if (index < 0) index = textsFR.length-1;
					$('#mainPhrase').html(textsFR[index]);
				} else {
					if (index < 0) index = textsEN.length-1;
					$('#mainPhrase').html(textsEN[index]);
				}
				morphText();
				$('#mainPhrase').show("slide", { direction: "right" }, 1000, function() {
					eventInProgress = false;
					index++;
				});
			});
		}
	});
	
	$('#mainPhrase').swiperight(function() {
		if (!eventInProgress) {
			eventInProgress = true;
			$('#mainPhrase').hide("slide", { direction: "right" }, 1000, function() {
				if (lang == 'FR') {
					if (index >= textsFR.length) index = 0;
					$('#mainPhrase').html(textsFR[index]);
				} else {
					if (index >= textsEN.length) index = 0;
					$('#mainPhrase').html(textsEN[index]);
				}
				morphText();
				$('#mainPhrase').show("slide", { direction: "left" }, 1000, function() {
					eventInProgress = false;
					index++;
				});
			});
		}
	});
	
	$('#index').bind('vmousedown', function(e) {
		if (tapHolding) {
			e.stopPropagation();
			scrolling = true;
			clearTimeout(timerScroll);
			startX = e.pageX;
			startY = e.pageY;
		}
	});
	
	$('#index').bind('vmousemove', function(e) {
		if (scrolling) {
			e.stopPropagation();
			if ((e.pageY > startY) && (indexList < sizeList)) {
				var variationY = parseInt((e.pageY - startY)/30);
				
				if (variationY > 0) {
					startY = e.pageY;
					ulList.eq(indexList).removeClass('li-selected');
					indexList += variationY;
					if (indexList > sizeList) { indexList = sizeList; }
					ulList.eq(indexList).addClass('li-selected');
					if (indexList == sizeList) {
						ulList.eq(indexList).html('<img src="./delete_selected.png" />');
						toDelete = true;
					}
				}
			}
			else if ((e.pageY < startY) && (indexList > 0)) {
				var variationY = parseInt((startY - e.pageY)/30);
				
				if (variationY > 0) {
					startY = e.pageY;
					ulList.eq(indexList).removeClass('li-selected');
					if (indexList == sizeList) {
						ulList.eq(indexList).html('<img src="./delete.png" />');
						toDelete = false;
					}
					indexList -= variationY;
					if (indexList < 0) { indexList = 0; }
					ulList.eq(indexList).addClass('li-selected');
				}
			}
		}
	});
	
	$('#index').bind('vmouseup', function(e) {
		if (scrolling) {
			e.stopPropagation();
			scrolling = false;
			timerScroll = setTimeout("scrollTimeOut()", waitTime);
		}
	});
	
	$('#index').delegate('#ul li','tap',function(e) {
		ulList.eq(indexList).removeClass('li-selected');
		$(this).addClass('li-selected');
		if (this == ulList(sizeList)) {
			$(this).html('<img src="./delete_selected.png" />');
			toDelete = true;
		}
		timerScroll = setTimeout("scrollTimeOut()", 50);
	});
	
	$('#index').bind("tap", function() {
		if (!eventInProgress) {
			eventInProgress = true;
			if (((new Date()).getTime() - lastTap) < 300) {
				// input
				inputFCT();
			}
			lastTap = (new Date()).getTime();
			eventInProgress = false;
		}
	});
	
	$('#index').bind("scrollstart", function(e) {
		e.preventDefault();
	});
	
	var arrayPage = $('div[data-role|="page"]');
	for (var i = 0; i < arrayPage.length; i++) {
		$(arrayPage[i]).css('height','100%');
		var footer = $(arrayPage[i]).children('div[data-role|="footer"]');
		var content = $(arrayPage[i]).children('div[data-role|="content"]');
		if (footer) {
			$(footer).css('height','10%');
			$(content).css('height','85%');
		} else {
			$(content).css('height','95%');
		}
	}
});

jQuery.fn.extend({
	disableSelection: function () {
		return this.each(function () {
			this.onselectstart = function () {
				return false;
			};
			this.unselectable = "on";
			jQuery(this).css('user-select', 'none');
			jQuery(this).css('-o-user-select', 'none');
			jQuery(this).css('-moz-user-select', 'none');
			jQuery(this).css('-khtml-user-select', 'none');
			jQuery(this).css('-webkit-user-select', 'none');
		});
	}
});

$('#input').ready(function(event) {
	$('#userInputSubmit').click(function () {
		$.mobile.changePage($('#index'), "pop", true);
		appendToCloud(phraseInput);
		userInput = $('#mainPhrase').html($('#userInput').val());
		morphText();
	});
	
	$('#input').bind("tap", function() {
		if (!eventInProgress) {
			eventInProgress = true;
			if (((new Date()).getTime() - lastTap) < 300) {
				$.mobile.changePage($('#index'), "pop", true);
			}
			lastTap = (new Date()).getTime();
			eventInProgress = false;
		}
	});
});

jQuery.extend({
	random: function (X) {
		return Math.floor(X * (Math.random() % 1));
	},
	randomBetween: function (MinV, MaxV) {
		return MinV + jQuery.random(MaxV - MinV + 1);
	}
});
